﻿chart = function () {
    var $objs = {
        stockChart:null
    }, settings = {
        now: new Date(),
        chartColor: { up: "#49c043", down: "#990f0f" }
    }

    timeChart = {
        find: function (data, time) {
            return data.filter(function (n, i) { return n[0] == time; });
        },
        lastTime: null,
        updatePointOnSeries: function (chart, i, px, point) {
            var last;
            return chart.series[i].points
                ? (last = chart.series[i].points[this.times[px]], last && (point.color
                    ? (last.graphic ? last.update(point.y, false) : last.update(point, false), last.graphic && last.graphic.attr("fill", point.color))
                    : (last.update(point, false))))
                : void 0
        },
        updatePoint: function (chart, data, i) {
            this.updatePointOnSeries(chart, 0, data.close[i][0], data.close[i]);
            this.updatePointOnSeries(chart, 1, data.volume[i].x, { y: data.volume[i].y, color: data.volume[i].color });
        },
        process: function (chart, data) {
            if (!chart || !chart.series || chart.series.length == 0 || !chart.series[0]) return false;
            var current, current_point, lastClose, diff;
            if (data.close.length > 2) {
                lastClose = data.close[0];
            }
            for (var i = 1; i < data.close.length; i++) {
                if (data.close.length > 2) {
                    diff = data.close[i][0] - lastClose[0];
                    while (diff > 6e4) {
                        lastClose[0] = lastClose[0] + 6e4
                        data.close.push([lastClose[0], lastClose[1]]);
                        data.volume.push({ x: lastClose[0], y: 0, color: settings.chartColor.up });
                        diff -= 6e4;
                    }
                    lastClose = data.close[i];
                }
                this.updatePoint(chart, data, i);
            }
        },
        polling: function () {
            timeChart.now = timeChart.now + 1e3 * 60;
                //console.log(new Date(timeChart.now - 8 * 1e3 * 60 * 60));
                timeChart.updatePointOnSeries($objs.stockChart, 0, timeChart.now, [timeChart.now, stock.close]);
                timeChart.updatePointOnSeries($objs.stockChart, 1, timeChart.now, { y: 0, color: settings.chartColor.up });

                $objs.stockChart.redraw(!0);
        },
        now: 0,
        times: {},
        build: function (data) {
            if ($objs.stockChart) $objs.stockChart.destroy();

            data = eval(data) || [];

            var open = stock.open;
            var lineColor = "#111";

            var startTime1 = Date.UTC(settings.now.getFullYear(), settings.now.getMonth(), settings.now.getDate(), 1, 0, 0, 0);
            var startTime2 = Date.UTC(settings.now.getFullYear(), settings.now.getMonth(), settings.now.getDate(), 12, 0, 0, 0);
            var now = timeChart.now = Date.UTC(settings.now.getFullYear(), settings.now.getMonth(), settings.now.getDate(), settings.now.getHours(), settings.now.getMinutes(), 0, 0);

            var time = startTime1, lineData = [], columnData = [],
                preClose = open, close = open, volume = null, trend, i = 0, findItem;

            this.lastTime = data.length >= 1 ? data.slice(-1)[0][0] : null;
            this.lastTime = this.lastTime < now ? now : this.lastTime;

            while (lineData.length <= 480) {
                time = i == 0 ? startTime1 : (i == 240 ? startTime2 : lineData.slice(-1)[0].x + (60 * 1000));

                findItem = this.find(data, time);

                close = findItem.length == 0 ? (time <= this.lastTime ? preClose : null) : findItem[0][4];
                volume = findItem.length == 0 ? (time <= this.lastTime ? 0 : null) : findItem[0][5];

                lineData.push({ x: time, y: close });

                if (close < preClose) {
                    trend = false;
                }
                else {
                    trend = true;
                }
                preClose = close;

                if (volume)
                    columnData.push({ x: time, y: volume, color: (trend ? settings.chartColor.up : settings.chartColor.down) });
                else
                    columnData.push({ x: time, y: volume });

                this.times[time] = i == 0 ? 0 : i;

                i++;
            }

            $objs.stockChart = new Highcharts.StockChart({
                chart: {
                    renderTo: "candlestick_chart",
                    animation: false,
                    marginTop: 55,
                    backgroundColor: "rgba(0,0,0, 0.0)",
                    events: {
                        load: function () {
                            stockChart.loading = false;
                            $("#candlestick_chart").mousemove(chartMove);
                        }
                    }
                },
                loading: {
                    style: {
                        backgroundColor: 'inherit',
                        opacity: 1
                    }
                },
                credits: { enabled: !1 },
                exporting: {
                    enabled: false
                },
                navigator: {
                    enabled: false
                },
                scrollbar: {
                    enabled: false
                },
                rangeSelector: {
                    enabled: false
                },
                tooltip: {
                    shared: true,
                    crosshairs: false,
                    valueDecimals: 2,
                    borderWidth: 0,
                    backgroundColor: "rgba(0,0,0,0)",
                    borderRadius: 2,
                    shadow: !1,
                    positioner: function (w, h, point) {
                        return { x: 0, y: 0 };
                    },
                    useHTML: !0,
                    formatter: function () {
                        var __out = [];
                        __out.push("<div class='chart-ticker'>"),
                        __out.push(R("kline-date", "日期：")),
                        __out.push("<span class=t-value>" + Highcharts.dateFormat(DATETIME_LABEL_FORMAT_FOR_TOOLTIP.minute[0], this.x) + "</span>"),
                        __out.push(R("kline-price", "成交价：")),
                        __out.push("<span class=t-value>" + this.points[0].y + "</span>"),
                        __out.push(R("kline-volume", "成交量：")),
                        __out.push("<span class=t-value>" + (this.points[1] ? this.points[1].y : 0) + "</span>");
                        __out.push("</div>")

                        return __out.join("");
                    }
                },
                plotOptions: {
                    series: {
                        dataGrouping: {
                            groupPixelWidth: 1
                        },
                        states: {
                            hover: {
                                enabled: false
                            }
                        }
                    },
                    column: {
                        colorByPoint: true
                    }
                },

                xAxis: {
                    lineColor: lineColor,
                    tickColor: lineColor,
                    tickInterval: 60 * 1000 * 60 * 2,
                    type: "datetime",
                    dateTimeLabelFormats: DATETIME_LABEL_FORMAT,
                    ordinal: true,
                    minorGridLineColor: lineColor,
                    minorGridLineWidth: 1,
                    minorTickInterval: 60 * 1000 * 60 * 1,
                    labels: {
                        formatter: function () {
                            var v = Highcharts.dateFormat(DATETIME_LABEL_FORMAT.minute, this.value);
                            return v == '12:00' ? '05:00/12:00' : v;
                        }
                    }
                },
                yAxis: [{
                    tickColor: lineColor,
                    gridLineColor: lineColor,
                    opposite: true,
                    labels: {
                        x: 0,
                        y: 2,
                        align: 'left',
                        formatter: function () {
                            return "<span" + (this.value < open ? " style='color:" + settings.chartColor.down + "'" : (this.value > open ? " style='color:" + settings.chartColor.up + "'" : "")) + ">{0}</span>".replace('{0}', this.value.toFixed(2));
                        },
                    },
                    height: '70%',
                    showFirstLabel: true,
                    showLastLabel: true,
                    //minorTickWidth: 1,
                    //minRange:20,
                    //tickAmount: 7,
                    min: open - open * 0.2 - 0.01,
                    max: open + open * 0.2 + 0.01,
                    //floor:open-open*0.2,
                    //ceiling:open+open*0.2,
                    //startOnTick:true,
                    //endOnTick:true,
                    startOnTick: false,
                    endOnTick: false,
                    tickInterval: (((open + open * 0.2) - (open - open * 0.2)) / 8),
                    plotLines: [{
                        value: open,
                        color: lineColor,
                        width: 3
                    }]

                }, {
                    tickColor: lineColor,
                    gridLineColor: lineColor,
                    offset: 0,
                    labels: {
                        x: 0,
                        align: 'left',
                    },
                    top: '75%',
                    height: '25%',
                    showFirstLabel: true,
                    showLastLabel: true,
                    //offset:0,
                    startOnTick: true,
                    endOnTick: true,
                    //tickPixelInterval:20,
                    //tickAmount:4
                }, { // slave axis
                    gridLineColor: lineColor,
                    linkedTo: 0,
                    opposite: false,
                    labels: {
                        useHTML: true,
                        formatter: function () {
                            var v = (((this.value - open) / open) * 100);
                            return "<span" + (v < 0 ? " style='color:" + settings.chartColor.down + "'" : (v > 0 ? " style='color:" + settings.chartColor.up + "'" : "")) + ">{0}</span>".replace('{0}', v.toFixed(2) + '%');
                        },
                        x: 0,
                        y: 2,
                        //align:'left'
                    },
                    height: '70%'

                }],
                series: [{
                    type: 'spline',
                    name: '成交价',
                    data: lineData,
                    lineWidth: 2,
                    lineColor: '#fff',

                }, {
                    type: 'column',
                    name: '成交量',
                    data: columnData,
                    turboThreshold: Number.MAX_VALUE,
                    yAxis: 1
                }]
            });
        }
    };
}